#!/bin/bash
# Author: Auroot/BaSierl
# Wechat：Auroot
# Script name：Auins (ArchLinux User Installation Scripts) 
# Arch Image: archlinux-2020.12.01-x86_64.iso [2021.1.1 - 2021.3.1]
# URL GitHub: https://github.com/BaSierL/arch_install.git
# URL Gitee : https://gitee.com/auroot/Auins.git
# Home URL: : https://www.auroot.cn
# set -xe
echo &>/dev/null
# 初始化变量
function Init_Global_Variable(){
    # The contents of the variable are customizable
    Version="ArchLinux user installation scripts V4.2.1" 
    Stript_Dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd )
    Module="${Stript_Dir}/Module" # The script module directory
    Temp_Data="${Stript_Dir}/Temp_Data" # Log Directory
    Configure_file="${Stript_Dir}/auins.conf"  # Configure file
    Configure_tmp_list="$Temp_Data/auin.info"  # Info file
    entries_a="/run/archiso/bootmnt/loader/entries/01-archiso-x86_64.conf"  # Uefi test
    entries_b="/run/archiso/bootmnt/loader/entries/01-archiso-x86_64-linux.conf"  # Boot test
    # Module URL: Default settings
    Branch="master"  # master: 稳定 preview: 测试
    gitUrl="https://gitee.com/auroot"
    AuinsUrl=${AuinsUrl:-${gitUrl}/Auins/raw/${Branch}}
    ModuleUrl=${ModuleUrl:-$AuinsUrl/Module}
    CPU_name=$(head -n 5 /proc/cpuinfo | grep "model name" | cut -d":" -f2)
}
# 系统配置变量
function System_Config_Global_Variable(){ 
    Area="/Asia/Shanghai"  # The area.
    PASS="123456"  # SSH password
}
# 程序包，默认预设 请不要改变量名(萌新),可以自己添加包
function Desktop_Package_Variable(){    
    # Font Package.
    Fonts_pkg="wqy-microhei wqy-zenhei ttf-dejavu ttf-ubuntu-font-family noto-fonts noto-fonts-extra noto-fonts-emoji noto-fonts-cjk ttf-dejavu ttf-liberation"
    # 常用软件 wps-office-cn wps-office-mime-cn wps-office-mui-zh-cn netease-cloud-music deepin-wine-wechat
    Common_pkg="neofetch unrar unzip p7zip zsh vim git mtpfs mtpaint libmtp kchmviewer file-roller openssh"
    # Desktop environment Package.
    XorgGroup_pkg="xorg xorg-server xorg-xinit mesa gwenview flameshot"
    Plasma_pkg="plasma plasma-meta plasma-desktop konsole dolphin dolphin-plugins kate plasma-pa kio-extras powerdevil kcm-fcitx ark"
    Gnome_pkg="gnome gnome-extra gnome-tweaks gnome-shell gnome-shell-extensions gvfs-mtp gvfs gvfs-smb gnome-keyring"
    Deepin_pkg="deepin deepin-extra lightdm-deepin-greeter"
    Xfce4_pkg="xterm xfce4 xfce4-goodies light-locker xfce4-power-manager libcanberra"
    i3wm_pkg="i3-wm i3lock i3blocks i3status rxvt-unicode compton dmenu feh picom nautilus polybar gvfs-mtp xfce4-terminal termite thunar"
    i3gaps_pkg="i3-gaps i3lock i3blocks i3status rxvt-unicode compton dmenu feh picom nautilus polybar gvfs-mtp xfce4-terminal termite thunar"
    mate_pkg="mate mate-extra"
    lxde_pkg="lxde" 
    Cinnamon_pkg="cinnamon blueberry gnome-screenshot gvfs gvfs-mtp gvfs-afc exfat-utils faenza-icon-theme accountsservice gnome-terminal"
    openbox_pkg="openbox ranger thunar rox obconf nitrogen tint2 rxvt-unicode feh menumaker xfce4-terminal slim gmrun xfce4-clipman-plugin highlight atool w3m poppler mediainfo" 
    # dwm_pkg="base-devel noto-fonts-cjk dmenu slock alacritty picom acpilight alsa-utils numlockx"
}
# 含引导程序包的变量
function Boot_Package_Variable(){   
    Bios_grub_Pkg="grub os-prober networkmanager dosfstools"
    Uefi_grub_Pkg="grub efibootmgr os-prober networkmanager"
}
# 含驱动程序包的变量 
function Driver_Package_Variable(){    # Driver Package.
    AudioDriver_Pkg="alsa-utils pulseaudio pulseaudio-bluetooth pulseaudio-alsa"
    inputDriver_Pkg="xf86-input-synaptics xf86-input-libinput"
    BluetoothDriver_Pkg="bluez bluez-utils blueman bluedevil"
    Intel_Pkg="xf86-video-intel intel-ucode xf86-video-intel xf86-video-intel mesa-libgl libva-intel-driver libvdpau-va-gl"
    Amd_Pkg="amd-ucode"
    Nvidia_A_Pkg="nvidia nvidia-utils opencl-nvidia lib32-nvidia-utils lib32-opencl-nvidia mesa lib32-mesa-libgl"
    Nvidia_B_Pkg="optimus-manager optimus-manager-qt"
}
# 脚本颜色变量
function Color_Global_Variable(){
    r='\033[1;31m'  #---红
    g='\033[1;32m'  #---绿
    y='\033[1;33m'  #---黄
    b='\033[1;36m'  #---蓝
    w='\033[1;37m'  #---白
    h='\033[0m'     #---后缀
    #-----------------------------#
    rw='\033[1;41m'  #--红白
    wg='\033[1;42m'  #--白绿
    ws='\033[1;43m'  #--白褐
    wb='\033[1;44m'  #--白蓝
    # wq='\033[1;45m'  #--白紫
    wa='\033[1;46m'  #--白青
    # bx='\033[1;4;36m'  #---蓝 下划线
    #-----------------------------#
    # 交互 蓝  红
    JHB=$(echo -e "${b}-=>${h} ")
    # JHR=$(echo -e "${r}-=>${h} ")
    # 交互 绿 黄
    # JHG=$(echo -e "${g}-=>${h} ")
    JHY=$(echo -e "${y}-=>${h} ")
    #-----------------------------
    # 提示 蓝 红
    PSB=$(echo -e "${b} ::==>${h}")
    PSR=$(echo -e "${r} ::==>${h}")
    # 提示 绿 黄
    PSG=$(echo -e "${g} ::==>${h}")
    PSY=$(echo -e "${y} ::==>${h}")
}
# 脚本自检函数
function facts(){
    #------检查必要目录或文件是否存在
    if [ ! -d "${Temp_Data}" ]; then
        mkdir -p "${Temp_Data}"
    fi
    if [ ! -d "${Module}" ]; then
        mkdir -p "${Module}"
    fi
    if [ ! -e "${Configure_tmp_list}" ]; then
        touch "${Configure_tmp_list}"
        echo -e "# This is not a profile.\n# Do not change one of the items.\nArchiso_Version_check=\nCPU_Name=\nCPU_Vendor=\nLinuxKernel=\nEthernet_ip=\nWifi_ip=\nPatterns=\nDisk=\nBios_Type=\nDisk_Type=\nBoot_partition=\nRoot_partition=\nSwap_file=\nSwap_size=\nVirtualization=\nDesktop_Env=\nDesktop_Mg=\nUsers=\nPassword=\nRoot_Password=\n" >> "$Configure_tmp_list"
    fi
    # boot
    if [ -d /sys/firmware/efi ]; then
        Bios_Type="Uefi"
        Disk_Type="gpt"
        sed -i "11c Bios_Type = Uefi" "$Configure_tmp_list"
        sed -i "12c Disk_Type = gpt" "$Configure_tmp_list"
    else
        Bios_Type="Bios"
        Disk_Type="dos"
        sed -i "11c Bios_Type = Bios" "$Configure_tmp_list"
        sed -i "12c Disk_Type = dos/mbr" "$Configure_tmp_list"
    fi
    if lscpu | grep GenuineIntel &>/dev/null ; then
        CPU_Vendor="intel"
        sed -i "5c CPU_Vendor = intel" "$Configure_tmp_list"
        sed -i "4c CPU_Name =${CPU_name}" "$Configure_tmp_list"
    elif lscpu | grep AuthenticAMD &>/dev/null ; then
        CPU_Vendor="amd"
        sed -i "5c CPU_Vendor = amd" "$Configure_tmp_list"
    fi
    # Virtualization
    if lspci | grep -i virtualbox &>/dev/null ; then
        Virtualization="virtualbox"
        sed -i "17c Virtualization = virtualbox" "$Configure_tmp_list"
    elif lspci | grep -i vmware &>/dev/null ; then
        Virtualization="vmware"
        sed -i "17c Virtualization = vmware" "$Configure_tmp_list"
    fi
    # 判断当前模式
    if [ -e /Temp_Data/Chroot ]; then
        ChrootPatterns="Chroot-ON"
        sed -i "9c Patterns = Chroot-ON" "$Configure_tmp_list"
    else
        ChrootPatterns="Chroot-OFF"
        sed -i "9c Patterns = Chroot-OFF" "$Configure_tmp_list" 
    fi
    # 检验Archiso是否最新
    if [ -e "$entries_a" ]; then
        entries="$entries_a"
    elif [ -e "$entries_b" ]; then
        entries="$entries_b"
    fi
    Query_Archiso_Version_check=$(Query_List _Templist_ Archiso_Version_check)
    if [ "X$Query_Archiso_Version_check" = "Xno" ] || [ "X$Query_Archiso_Version_check" = "X" ]; then
        Archiso_Version_check "$entries"
    fi
    ln -sf /usr/share/zoneinfo"$Area" /etc/localtime &>/dev/null && hwclock --systohc
}
# 查询列表 Query_List _Config_ [内容] | Query_List _Templist_ [内容]
function Query_List(){    
    local List_options=${1} List_Query=${2}
    case ${List_options} in
        _Config_)
            Temp_list=$(cat "$Configure_file")
        ;;
        _Templist_)
            Temp_list=$(cat "$Configure_tmp_list")
        ;;
    esac 
    echo "${Temp_list}" | grep "$List_Query" | cut -d"=" -f2
    # for i in ${Temp_list[*]}; do
    #     if [[ "$i" =~ $List_Query ]]; then
    #         echo "$i" | cut -d"=" -f2
    #     fi 
    # done
}
# 下载所需的脚本模块
function Update_Module(){    
    if [ ! -e "$Module/mirrorlist.sh" ]; then
        curl -fsSL "$ModuleUrl/mirrorlist.sh" > "${Module}/mirrorlist.sh" 
        chmod +x "$Module/mirrorlist.sh"
    fi
    if [ ! -e "$Module/useradd.sh" ]; then
        curl -fsSL "$ModuleUrl"/useradd.sh > "${Module}/useradd.sh"
        chmod +x "$Module/useradd.sh"
    fi
    if [ ! -e "$Module/Process_manage.sh" ]; then
        curl -fsSL "$ModuleUrl"/Process_manage.sh > "${Module}/Process_manage.sh"
        chmod +x "$Module/Process_manage.sh"
    fi
    if [ ! -e "${Configure_file}" ]; then
        curl -fsSL "$AuinsUrl"/install.conf > "$Configure_file"
    fi
}
# Auins的帮助文档
function Auin_help(){
    echo "${Version}"
    echo -e "Auins is a script for ArchLinux installation and deployment.\n"
    echo -e "usage: auin [-h] [-V] command ...\n"
    echo "Optional arguments:"
    echo "  -m --mirror   Automatically configure mirrorlist file and exit."
    echo "  -w --cwifi    Connect to a WIFI and exit."
    echo "  -s --openssh  Open SSH service (default password: 123456) and exit."
    echo "  -vm --virtual Install Vmware/Virtualbox Tools and exit."
    echo "  -i --info     View the computer information of script record, file: ./Temp_ Data/auin.info"
    echo "  -h --help     Show this help message and exit. "
    echo "  -V --version  Show the conda version number and exit."
}
# Auins的其他选项功能
function Auin_Options(){
    local Function_Enter="${1}"
    case ${Function_Enter} in
        -m | --mirror)
            bash "${Module}/mirrorlist.sh"
            exit 0;
        ;;
        -w | --cwifi)
            Info_Ethernet;
            Configure_wifi;
            exit 0;
        ;;
        -s | --openssh)
            Info_Ethernet;
            Open_SSH;
            exit 0;
        ;;
        -vm | --vmtools)
            install_virtualization_service;
        ;;
        -i | --info)
            echo "---------------------------------"
            cat "${Configure_tmp_list}"
            echo "================================="
            exit 0;
        ;;
        -h | --help)
            Auin_help
            exit 0;
        ;;
        -v | -V | --version)
            clear;
            version
            exit 0;
        ;;
        -shell)
            Shell_Exec
        ;;
    esac
}
# Auins版本号，Stript Version
function version(){    
    echo -e "${wg}${Version}${h}"
    echo -e "${wg}$(grep "archisolabel=" < "$entries" | grep -v grep | awk '{print $3}')${h}\n"
    echo -e "${wa}Author:${h} Auroot/BaSierl"
    echo -e "${rw}blog  :${h} www.auroot.cn"
    echo -e "${wb}URL Gitee :${h} https://gitee.com/auroot/Auins.git"
    
}

# 获取本机IP地址，并储存到$Configure_tmp_list， Network Variable
function Info_Ethernet(){    
    local Info_Nic
    for  ((Cycle_number=3;Cycle_number<=10;Cycle_number++)); do
        Info_Nic=$(cut -d":" -f1 /proc/net/dev | sed -n "$Cycle_number",1p | sed 's/^[ ]*//g')
        if echo "$Info_Nic" | grep "en" &>/dev/null ; then 
            Ethernet_Name="$Info_Nic"
            Ethernet_ip=$(ip route list | grep "${Ethernet_Name}" | cut -d" " -f9 | sed -n '2,1p')
            sed -i "7c Ethernet_ip = ${Ethernet_ip:-Not}" "$Configure_tmp_list"
        elif echo "$Info_Nic" | grep "wl" &>/dev/null ; then
            Wifi_Name="$Info_Nic"
            Wifi_ip=$(ip route list | grep "${Wifi_Name}" | cut -d" " -f9 | sed -n '2,1p') 
            sed -i "8c Wifi_ip = ${Wifi_ip:-Not}" "$Configure_tmp_list"
        fi
    done    
}
# 配置WIFI，Configure WIFI
function Configure_wifi() {
    local Output_WIFI_SSID Output_WIFI_PASS
    Output_WIFI_SSID=$(echo -e "${PSG} ${g} Wifi SSID 'TP-Link...' :${h} ${JHB}")
    Output_WIFI_PASS=$(echo -e "${PSG} ${g} Wifi Password :${h} ${JHB}")
    read -rp "${Output_WIFI_SSID}" WIFI_SSID
    read -rp "${Output_WIFI_PASS}" WIFI_PASSWD
    iwctl --passphrase "$WIFI_PASSWD" station "$Wifi_Name" connect "$WIFI_SSID"
    sleep 2;
    ip address show "${Wifi_Name}"
    if ! ping -c 3 -i 2 -W 5 -w 30 8.8.8.8; then
        echo "Network ping check failed. Cannot continue."
        Process_Management stop "$0"
    fi
}
# 配置有线网络，Configure Ethernet.
function Configure_Ethernet(){
    echo ":: One moment please............"
    ip link set "${Ethernet_Name}" up
    ip address show "${Ethernet_Name}"
    ping -c 3 -i 2 -W 5 -w 30 8.8.8.8
    sleep 1;
}
# 开启SSH服务， Start ssh service  [可优化：1.自定义用户名与密码，2.配置ssh文件]
function Open_SSH(){    
    echo
    echo -e "${y}:: Setting SSH Username / password.${h}" 
    echo "${USER}:${PASS}" | chpasswd &>/dev/null 
    echo -e "${g} ||=================================||${h}"
    echo -e "${g}       $ ssh $USER@${Ethernet_ip:-IP_Addess..}  ${h}" 
    echo -e "${g}       $ ssh $USER@${Wifi_ip:-IP_Addess..}      ${h}"
    echo -e "${g}       Username --=>  $USER           ${h}"
    echo -e "${g}       Password --=>  $PASS           ${h}"
    echo -e "${g} ||=================================||${h}"
    systemctl start sshd.service 
    netstat -antp | grep sshd 
}
# 设置root密码 用户  判断/etc/passwd文件中最后一个用户是否大于等于1000的普通用户，如果没有请先创建用户
function ConfigurePassworld(){
    UserName=$(Query_List _Templist_ Users) 
    if [ "${UserName}" != "" ]; then   #  设定一个文件匹配，这个文件在不在都无所谓
        PasswdFile="/etc/passwd"
        for ((Number=1;Number<=50;Number++))  # 设置变量Number 等于1 ；小于等于50 ； Number 1+1直到50
        do
        Query=$(tail -n "${Number}" "${PasswdFile}" | head -n 1 | cut -d":" -f3)
            for Contrast in {1000..1100}
            do
                if [[ $Query -eq $Contrast ]]; then
                    CheckingUsers=$(grep "$Query" < ${PasswdFile} | cut -d":" -f1)
                    CheckingID=$(grep "$Query" < ${PasswdFile} | cut -d":" -f3)
                fi
            done 
        done
        echo -e "${PSG} ${g}A normal user already exists, The UserName:${h} ${b}${CheckingUsers}${h} ${g}ID: ${b}${CheckingID}${h}." 
        sleep 2;
    else
        bash "${Module}/useradd.sh" "${Configure_tmp_list}"
        UserName=$(Query_List _Templist_ Users) 
        echo -e "${PSG} ${g}A normal user already exists, The UserName:${h} ${b}${UserName}${h}." 
        sleep 2;
    fi
}
# 安装系统、内核、基础包等，Install system kernel / base...
function Install_Archlinux(){    
    echo -e "${wg}Update the system clock.${h}"   # update time
    timedatectl set-ntp true
    sleep 2;
    echo -e "\n${PSG} ${g}Install the base packages.${h}\n"
    bash "${Module}/mirrorlist.sh"
    pacstrap -i /mnt linux base base-devel linux-firmware networkmanager net-tools vim #  linux base 
    sleep 2;
    echo -e "\n${PSG}  ${g}Configure Fstab File.${h}"   # Configure fstab file
    genfstab -U /mnt >> /mnt/etc/fstab  
    LinuxKernel=$(arch-chroot /mnt /usr/bin/uname -a | /usr/bin/cut -d"#" -f1)
    sed -i "6c LinuxKernel = ${LinuxKernel}" "$Configure_tmp_list" 
    cp -rf "${Temp_Data}" "/mnt/" 
    cp -rf "${Module}" "/mnt/" 
    cat "$0" > /mnt/auin.sh  && chmod +x /mnt/auin.sh 
    touch /mnt/Temp_Data/Chroot && echo "Chroot=ON" > /mnt/Temp_Data/Chroot
}
# Chroot -> /mnt 
function Auin_chroot(){    
    cat "$0" > /mnt/auin.sh  && chmod +x /mnt/auin.sh
    arch-chroot /mnt /bin/bash -c "/auin.sh"
}
# 类型判断 获取磁盘[\_partition\_], 获取分区[\_partition_root\_], 获取磁盘类型[\_Disk_Type\_], 挂载分区[\_Open_mount\_] [磁盘] [目录].
function partition_facts(){
    disk_options=${1}
    diskName=${2}
    mountDir=${3}
    case ${disk_options} in
        _partition_)  
            State="false"
            if echo "${diskName}" | cut -d"/" -f3 | grep -E "^[a-z]d[a-z]$|^nvme|^mmc" &>/dev/null  ; then
                userinput_disk=$(echo "${diskName}" | cut -d"/" -f3 | grep -E "^[a-z]d[a-z]$|^nvme|^mmc")
                State="true"
            else
                State="false"
            fi
        ;;
        _partition_root_)  
            State="false"
            if echo "${diskName}" | cut -d"/" -f3 | grep -E "^[a-z]d[a-z][1-9]|^nvme*|^mmc*" &>/dev/null  ; then
                userinput_disk=$(echo "${diskName}" | cut -d"/" -f3 | grep -E "^[a-z]d[a-z][1-9]|^nvme*|^mmc*")
                State="true"
            else
                State="false"
            fi
        ;;
        _Disk_Type_)
            if ! fdisk -l /dev/"$userinput_disk" | grep "Disklabel type:" ; then
                user_Disk_Type="false"
            elif fdisk -l /dev/"$userinput_disk" | grep "gpt" ; then
                user_Disk_Type="gpt"
            elif fdisk -l /dev/"$userinput_disk" | grep "dos" ; then
                user_Disk_Type="dos"
            elif fdisk -l /dev/"$userinput_disk" | grep "sgi" ; then
                user_Disk_Type="sgi"
            elif fdisk -l /dev/"$userinput_disk" | grep "sun" ; then
                user_Disk_Type="sun"
            fi
        ;;
        _Open_mount_)
            if ! mountpoint -q "$mountDir" ; then  # /proc/self/mountinfo
                mount "$diskName" "$mountDir"
            else
                umount -R "$mountDir" &>/dev/null
                mount "$diskName" "$mountDir"
            fi
        ;;
    esac
}
# 判断使用的磁盘是否符合当前系统要求，并自定义改变[dos/gpt]
function partition_type(){
    local read_text_output
    partition_facts _Disk_Type_ "$input_disk"
    lsblk | grep -E "^[a-z]d[a-z]|^nvme|^mmc"|grep -v "grep" 
    echo;
    if [[ "$user_Disk_Type" != "$Disk_Type" ]] ; then
        echo -e "$PSR ${r} The boot does not match the disk ${b}[$Bios_Type] ${r}not ${b}[$user_Disk_Type]$h${r}.$h"
        read_text_output=$(echo -e "\n$PSY ${y}Whether to convert Disklabel type ->${b}[$Disk_Type]${y}? [y/N]:$h $JRY")
        read -rp "${read_text_output}" user_input
        case "$user_input" in
            [Yy]*)
                if [[ "$Disk_Type" = "gpt" ]] ; then
                    Disk_Type="gpt"
                elif [[ "$Disk_Type" = "dos" ]] ; then
                    Disk_Type="msdos"   
                fi
                parted /dev/"$userinput_disk" mklabel "$Disk_Type" -s
            ;;
            [Nn]*)
                echo -e "\n$PSR ${r} Error: Disklabel type${b}[$user_Disk_Type] ${r}not match and cannot be install System.$h"
                Process_Management stop "$0"
            ;;
            *)
                if [[ "$Disk_Type" = "gpt" ]] ; then
                    Disk_Type="gpt"
                elif [[ "$Disk_Type" = "dos" ]] ; then
                    Disk_Type="msdos"   
                fi
                parted /dev/"$userinput_disk" mklabel "$Disk_Type" -s
            ;;
        esac 
    else 
        echo -e "\n${PSG} ${g}Currently booted with ${b}[${Bios_Type}]. ${g}Select disk type: ${b}[${Disk_Type}].${h}"
    fi 
}
# 磁盘分区
function partition(){
    local read_text_output
    echo;lsblk -o+UUID | grep -E "sd.|nvme|mmc"    # 显示磁盘
    read_text_output=$(echo -e "\n${PSY} ${y}Select disk: ${g}/dev/sdX | sdX ${h}${JHB}")
    read -rp "${read_text_output}"  input_disk  #给用户输入接口
    partition_facts _partition_ "$input_disk"
    partition_type
    if [[ "$State" = "true" ]] ; then    
        cfdisk "/dev/$userinput_disk" && sed -i "10c Disk = /dev/$userinput_disk" "$Configure_tmp_list"
    else
        echo -e "\n${PSR} ${r} [cfdisk] Error: Please input: /dev/sdX | sdX? !!! ${h}"  
        Process_Management stop "$0"
    fi
}
# 格式化并挂载 引导分区，输入: /dev/sdX[0-9] | sdX[0-9]
function partition_booting(){
    local read_text_output
    echo;lsblk -o+UUID | grep -E "sd.|nvme|mmc|mmc" | grep -E "sd.|nvme|mmc"  
    read_text_output=$(echo -e "\n${PSY} ${y}Choose your EFI / BOOT partition: ${g}/dev/sdX[0-9] | sdX[0-9] ${h}${JHB}")
    read -rp "${read_text_output}" input_booting
        #设置输入”/dev/sda” 或 “sda” 都输出为 sda
        partition_facts _partition_root_ "$input_booting"
        if [[ "$State" = "true" ]] ; then
            mkfs.vfat "/dev/$userinput_disk" 
            if [[ "$Bios_Type" = "Uefi" ]] ; then
                if ! ls /mnt/boot/efi &>/dev/null ; then
                    mkdir -p /mnt/boot/efi
                fi
                partition_facts _Open_mount_ "/dev/$userinput_disk" /mnt/boot/efi
                sed -i "13c Boot_partition = /dev/$userinput_disk" "$Configure_tmp_list"
            else
                mkdir -p /mnt/boot &>/dev/null 
                umount -R /mnt/boot 2&>/dev/null
                mount "/dev/$userinput_disk" /mnt/boot 
                sed -i "13c Boot_partition = /dev/$userinput_disk" "$Configure_tmp_list"
            fi
        else
            echo -e "\n${r} ==>> [EFI] Error: Please input: /dev/sdX[0-9] | sdX[0-9] !!! ${h}"  
            Process_Management stop "$0"
        fi
}
# 格式化并挂载Root分区, 输入: /dev/sdX[0-9] | sdX[0-9]
function partition_root(){
    local read_text_output
    echo;lsblk -o+UUID | grep -E "sd.|nvme|mmc" | grep -E "sd.|nvme|mmc"  
    read_text_output=$(echo -e "\n${PSY} ${y}Choose your root[/] partition: ${g}/dev/sdX[0-9] | sdX[0-9] ${h}${JHB}")
    read -rp "${read_text_output}"  input_root   
    partition_facts _partition_root_ "$input_root"
    if [[ "$State" = "true" ]] ; then
        if ! mkfs.ext4 "/dev/$userinput_disk" ; then
            sleep 1;
        fi 
        umount -R /mnt/boot &>/dev/null
        umount -R /mnt/boot/efi &>/dev/null
        partition_facts _Open_mount_ "/dev/$userinput_disk" /mnt
        sed -i "14c Root_partition = /dev/$userinput_disk" "$Configure_tmp_list"
    else
        echo -e "\n${PSR} ${r} [root] Error: Please input: /dev/sdX[0-9] | sdX[0-9] !!! ${h}"  
        Process_Management stop "$0"
    fi
}
# 格式化并挂载虚拟的Swap分区，可自定义大小
function partition_swap(){
    local read_text_output
    echo;lsblk -o+UUID | grep -E "sd.|nvme|mmc" | grep -E "sd.|nvme|mmc"  
    read_text_output=$(echo -e "\n${PSY} ${y}lease select the size of swapfile: ${g}[example:256M-10000G ~] ${y}Skip: ${g}[No]${h} ${JHB}")
    read -rp "${read_text_output}"  input_swap_size
    case ${input_swap_size} in
        [Nn]* )
            echo -e "${wg} ::==>> Partition complete. ${h}"  
            sleep 1
            bash "${0}"
        ;;
        * )
            if echo "$input_swap_size" | grep -E "^[0-9]*[A-Z]$" &>/dev/null ; then
                echo -e "${PSG} ${g}Assigned Swap file Size: ${input_swap_size} .${h}"
                fallocate -l "${input_swap_size}" /mnt/swapfile 
                chmod 600 /mnt/swapfile 
                mkswap /mnt/swapfile 
                swapon /mnt/swapfile 
                sed -i "15c Swap_file = /mnt/swapfile" "$Configure_tmp_list"
                sed -i "16c Swap_size = ${input_swap_size}" "$Configure_tmp_list"
            else
                echo -e "\n${PSY} ${y}Skip create a swap file.${h}"  
                sleep 2;
                Process_Management stop "$0"
            fi
        ;;
    esac 
}
# 首选项 [4] 的列表
function input_System_Module(){    # print list 4
    echo -e "\n     ${w}*** ${r}Install System Module ${w}***${h}  "  
    echo "---------------------------------------------"
    echo -e "${PSY} ${g}   Disk partition.         ${r}**  ${w}[1]${h}"
    echo -e "${PSY} ${g}   Install System Files.   ${r}**  ${w}[2]${h}"
    echo -e "${PSY} ${g}   Configurt System.       ${r}**  ${w}[3]${h}"
    echo -e "${PSG} ${g}   Installation Desktop.   ${b}*   ${w}[4]${h}"  
    echo -e "${PSG} ${g}   Installation Drive.     ${b}*   ${w}[11]${h}" 
    echo -e "${PSY} ${g}   Install virtual tools.  ${b}*   ${w}[22]${h}"
    echo -e "${PSY} ${g}   arch-chroot /mnt.       ${r}**  ${w}[0]${h}"
    echo -e "---------------------------------------------\n" 
}
# 桌面环境选择列表
function input_Desktop_env(){
    echo -e "\n     ${w}***${h} ${b}Install Desktop${h} ${w}***${h}  "  
    echo "------------------------------------------------"
    echo -e "${PSB} ${g}   KDE plasma.     ${b}[1]  ${b}default: sddm${h}"
    echo -e "${PSB} ${g}   Gnome.          ${w}[2]  ${w}default: gdm${h}"
    echo -e "${PSB} ${g}   Deepin.         ${b}[3]  ${b}default: lightdm${h}"    
    echo -e "${PSB} ${g}   Xfce4.          ${w}[4]  ${w}default: lightdm${h}"  
    echo -e "${PSB} ${g}   i3wm.           ${b}[5]  ${b}default: sddm${h}"
    echo -e "${PSB} ${g}   i3gaps.         ${w}[6]  ${w}default: lightdm${h}"
    echo -e "${PSB} ${g}   lxde.           ${b}[7]  ${b}default: lxdm${h}"
    echo -e "${PSB} ${g}   Cinnamon.       ${w}[8]  ${w}default: lightdm${h}"
    echo -e "${PSB} ${g}   Mate.           ${b}[9]  ${b}default: lightdm${h}"
    echo -e "${PSB} ${g}   Openbox.        ${b}[10] ${b}default: sddm${h}"
    #echo -e "${PSB} ${g}   Dwm.        ${b}[10] ${b}default: sddm${h}"
    echo -e "------------------------------------------------\n"                          
}
# 桌面管理器选择列表，选择后，自动安装及配置服务；
function Desktop_Manager(){
    local read_text_output 
    echo "---------------------------------"
    echo -e "${PSB} ${g}   sddm.     ${w}[1]${h}"  
    echo -e "${PSB} ${g}   gdm.      ${w}[2]${h}" 
    echo -e "${PSB} ${g}   lightdm.  ${w}[3]${h}"   
    echo -e "${PSB} ${g}   lxdm.     ${w}[4]${h}"  
    echo -e "${PSB} ${g}   default.  ${w}[*]${h}" 
    echo "---------------------------------"
    read_text_output=$(echo -e "${PSG} ${y} Please select Desktop Manager: ${h} ${JHB}")
    read -rp "${read_text_output}" DM_ID
    case ${DM_ID} in
        1)
            DmS="sddm"
        ;;
        2)
            DmS="gdm"  
        ;;
        3)
            DmS="lightdm"
        ;;
        4)
            DmS="lxdm"
        ;;
        *)
            sleep 1
        ;;
    esac
    echo ${DmS} > "${Temp_Data}/Desktop_Manager"
        if [[ ${DmS} == "sddm" ]] ; then
            Install_Program sddm sddm-kcm  # Install SDDM
            systemctl enable sddm
            sed -i "19c Desktop_Mg = ${DmS}" "$Configure_tmp_list"
        elif [[ ${DmS} == "gdm" ]] ; then
            Install_Program gdm     
            systemctl enable gdm  
            sed -i "19c Desktop_Mg = ${DmS}" "$Configure_tmp_list"
        elif [[ ${DmS} == "lightdm" ]] ; then
            Install_Program lightdm lightdm-gtk-greeter 
            systemctl enable lightdm
            sed -i "19c Desktop_Mg = ${DmS}" "$Configure_tmp_list"
        elif [[ ${DmS} == "lxdm" ]] ; then
            Install_Program lxdm
            systemctl enable lxdm 
            sed -i "19c Desktop_Mg = ${DmS}" "$Configure_tmp_list"
        fi
}
# 桌面环境安装函数 $1(桌面名称) $2(xinitrc配置 "exec desktop") $3(包列表)
function Install_DesktopEnv(){
    echo -e "${PSG} ${g}Configuring desktop environment.${h}"
    sleep 1;
    Install_Program "$XorgGroup_pkg"
    Install_Program "$3"
    Install_Program "$Common_pkg"
    Desktop_Manager
    Desktop_Env_Config "$1" "$2" # $1(Desktop name) $2(xinitrc "exec desktop")
    sed -i "18c Desktop_Env = $1" "$Configure_tmp_list"
}
# 桌面环境最终安装函数，在提示中输入序号即可自动安装;
function Set_Desktop_Env(){
    local read_text_output
    input_Desktop_env
    read_text_output=$(echo -e "${PSG} ${y} Please select desktop${h} ${JHB}")
    DESKTOP_ID="0"   
    read -rp "${read_text_output}"  DESKTOP_ID
    case ${DESKTOP_ID} in
        1)
            Install_DesktopEnv plasma startkde "$Plasma_pkg"
            DmS="sddm"
        ;;
        2)
            Install_DesktopEnv gnome gnome-session "$Gnome_pkg"
            DmS="gdm"
        ;;
        3)
            Install_DesktopEnv deepin startdde "$Deepin_pkg"  
            DmS="lightdm"
        ;;
        4)
            Install_DesktopEnv xfce4 startxfce4 "$Xfce4_pkg"
            DmS="lightdm"
        ;;
        5)
            Install_DesktopEnv i3wm i3 "$i3wm_pkg"
            # sed -i 's/i3-sensible-terminal/--no-startup-id termite/g' /home/"${CheckingUsers}"/.config/i3/config  # 更改终端
            DmS="sddm"
        ;;
        6)
            Install_DesktopEnv i3gaps i3 "$i3gaps_pkg"
            DmS="lightdm"
        ;;
        7)
            Install_DesktopEnv lxde startlxde "$lxde_pkg"
            DmS="lxdm"
        ;;
        8)
            Install_DesktopEnv cinnamon cinnamon-session "$Cinnamon_pkg"
            DmS="lightdm"
        ;;
        9)
            Install_DesktopEnv mate mate "$mate_pkg"
            DmS="lightdm"
        ;;
        10)  
            function openboxManger(){
                local openboxDir openboxTheme
                Desktop_Env_Config "openbox" "openbox-session" #  $1 # Desktop name $2 xinitrc "exec desktop"
                openboxDir="${UserHomeDir}/.config/openbox"
                openboxTheme="${UserHomeDir}/.themes"
                tint2Theme="${UserHomeDir}/.config/tint2/theme"
                mkdir -p "${openboxDir}" &>/dev/null
                rm -rf "${openboxTheme}" &>/dev/null
                rm -rf "${tint2Theme}" &>/dev/null
                cp /etc/xdg/openbox/{rc.xml,menu.xml,autostart,environment} "${openboxDir}" &>/dev/null
                curl -fsSL ${gitUrl}/Auins/raw/master/Module/Arch_auroot.jpg > "${openboxDir}"/Arch_auroot.jpg
                # openbox-theme
                git clone ${gitUrl}/openbox-theme-collections "${openboxTheme}"
                sed -i 's/Clearlooks/Triste-Froly/' "${openboxDir}"/rc.xml
                # .config/openbox/autostart 
                echo -e "tint2 -c ${UserHomeDir}/.config/tint2/theme/minima/minima.tint2rc &\nnitrogen --restore\nfeh --bg-fill ""${openboxDir}""/Arch_auroot.jpg\nxfce4-clipman &" >> "${openboxDir}"/autostart
                # Configure ranager
                curl -fsSL ${gitUrl}/Auins/raw/master/Module/rangerRc.sh > "$UserHomeDir"/rangerRc.sh
                curl -fsSL ${gitUrl}/Auins/raw/master/Module/obconf.sh > "$UserHomeDir"/obconf.sh
                echo -e "bash $UserHomeDir/rangerRc.sh ${UserHomeDir} \nsleep 3;" >> "${openboxDir}"/autostart
                echo -e "bash $UserHomeDir/obconf.sh&\nsleep 3;" >> "${openboxDir}"/autostart
                # tint2-theme   tint2 -c /home/"$CheckingUsers"/.config/tint2/theme/minima/minima.tint2rc &
                git clone ${gitUrl}/tint2-theme-collections "${tint2Theme}"
                # URxvt-themes
                curl -fsSL ${gitUrl}/URxvt-themes/raw/master/smooth-white-blue > /home/"$CheckingUsers"/.Xresources
                chown -R "$CheckingUsers":users "${UserHomeDir}"
                echo -e "sed -i '/obconf\|sed\|rangerRc/d' ${openboxDir}/autostart" >> "${openboxDir}"/autostart
            }
            echo -e "${PSG} ${g}Configuring desktop environment.${h}"
            sleep 1;
            Install_Program "$XorgGroup_pkg"
            Install_Program "${openbox_pkg}"
            Install_Program "$Common_pkg"
            sleep 1;
            slimTips=$(echo -e "${PSG} ${g} Using the default Desktop manager:'${b}slim${g}'[Y/*]?${h} ${JHB}")
            read -rp  "${slimTips}" slim_ID
            case "$slim_ID" in
                [Yy]*)
                    openboxManger;
                    # /usr/share/slim/themes   /etc/slim.conf }
                    git clone ${gitUrl}/slim_themes.git /home/"$CheckingUsers"/slim_themes
                    cp -rf /home/"$CheckingUsers"/slim_themes/themes/* /usr/share/slim/themes  
                    cp -rf /home/"$CheckingUsers"/slim_themes/previews /usr/share/slim/themes  
                    local themesNum numlockNum
                    themesNum=$(sed -n '/current_theme/=' /etc/slim.conf)
                    numlockNum=$(sed -n '/# numlock/=' /etc/slim.conf)
                    sed -i "${numlockNum}s/# numlock/numlock/g" /etc/slim.conf
                    sed -i "${themesNum}s/default/minimal/g" /etc/slim.conf
                    systemctl enable slim
                ;;
                *)
                    Desktop_Manager;
                    openboxManger;
                ;;
            esac
        ;;
        # 11)
        #     Install_DesktopEnv Dwm Dwm "$dwm_pkg"
        #     DmS="lightdm"
        # ;;
        *)
            echo -e "${PSR} ${r} Selection error.${h}"    
            Process_Management stop "$0"
        esac 
}
# 桌面环境配置函数
function Desktop_Env_Config(){
    if [ -e /home/"$CheckingUsers"/.xinitrc ];then
        echo -e "${PSR} ${y}Repeated execution !${h}";sleep 2; 
    else
        xinitrc_file="/etc/X11/xinit/xinitrc"
        startLine=$(sed -n '/twm &/=' $xinitrc_file) #先计算带adc字符串行的行号
        lineAfter=4
        endLine=$(("$startLine" + "$lineAfter"))
        sed -i "$startLine"','"$endLine"'d' "$xinitrc_file"
        echo "exec ${2}" >> /etc/X11/xinit/xinitrc 
        cp -rf /etc/X11/xinit/xinitrc  /home/"$CheckingUsers"/.xinitrc 
        echo -e "${PSG} ${w}${1} ${g}Desktop environment configuration completed.${h}"  
        sleep 2;   
    fi
}
function Install_Font(){
    local read_text_output
    read_text_output=$(echo -e "${PSG} ${y}Whether to install the Font. Install[y] No[*]${h} ${JHB}")
    read -rp "${read_text_output}" UserInf_Font
    case ${UserInf_Font} in
        [Yy]*)
            Install_Program "$Fonts_pkg" # install Fonts pkg
        ;;
    esac
}
# 包安装函数
function Install_Program() {
    set +e
    IFS=' ' PACKAGES=("$@")
    for VARIABLE in {1..3}
    do
        if ! pacman -Syu --noconfirm --needed ${PACKAGES[@]} ; then
            sleep 2;
        else
            break;
        fi
    done
    echo "$VARIABLE" &> /dev/null
    set -e
}
# Install I/O Driver
function Install_Io_Driver(){
    echo -e "${PSG} ${g}Installing Audio driver.${h}"  
    Install_Program "$AudioDriver_Pkg"
    systemctl enable alsa-state.service
    echo "load-module module-bluetooth-policy" >> /etc/pulse/system.pa
    echo "load-module module-bluetooth-discover" >> /etc/pulse/system.pa
    echo -e "${PSG} ${g}Installing input driver.${h}"  
    Install_Program "$inputDriver_Pkg"
    echo -e "${PSG} ${g}Installing Bluetooth driver.${h}"  
    Install_Program "$BluetoothDriver_Pkg"
}
# Install CPU GPU Driver
function Install_Processor_Driver(){
    local read_text_output
    echo -e "\n$PSG ${g}Install the cpu ucode and driver.$h"
    if [[ "$CPU_Vendor" = 'intel' ]]; then
        Install_Program "$Intel_Pkg"
    elif [[ "$CPU_Vendor" = 'amd' ]]; then
        Install_Program "$Amd_Pkg"
    else
        read_text_output=$(echo -e "${PSG} ${y}Please select: Intel[1] AMD[2].${h} ${JHB}")
        read -rp "${read_text_output}"  DRIVER_GPU_ID
        case $DRIVER_GPU_ID in
            1)
                Install_Program "$Intel_Pkg"
            ;;
            2)
                Install_Program "$Amd_Pkg"
            ;;
        esac
    fi
    lspci -k | grep -A 2 -E "(VGA|3D)"  
    read_text_output=$(echo -e "\n${PSG} ${y}Whether to install the Nvidia driver? [y/N]:${h} ${JHB}") 
    read -rp "${read_text_output}"  DRIVER_NVIDIA_ID
    case $DRIVER_NVIDIA_ID in
        [Yy]*)
            Install_Program "$Nvidia_A_Pkg"
            yay -Sy --needed "$Nvidia_B_Pkg"
            systemctl enable optimus-manager.service 
            rm -f /etc/X11/xorg.conf 2&>/dev/null
            rm -f /etc/X11/xorg.conf.d/90-mhwd.conf 2&>/dev/null
            if [ -e "/usr/bin/gdm" ] ; then  # gdm manager
                Install_Program gdm-prime
                sed -i 's/#.*WaylandEnable=false/WaylandEnable=false/'  /etc/gdm/custom.conf
            elif [ -e "/usr/bin/sddm" ] ; then
                sed -i 's/DisplayCommand/# DisplayCommand/' /etc/sddm.conf
                sed -i 's/DisplayStopCommand/# DisplayStopCommand/' /etc/sddm.conf
            fi
        ;;
        [Nn]* )
            bash "$0"
        ;;
        * )
        Process_Management stop "$0"
        ;;
        esac   
}
# Install/Configure Grub
function Configure_Grub(){
    echo -e "${wg}Installing grub tools.${h}"  #安装grub工具   UEFI与Boot传统模式判断方式：ls /sys/firmware/efi/efivars  
    if ls /sys/firmware/efi/efivars &>/dev/null ; then    # 判断文件是否存在，存在为真，执行EFI，否则执行 Boot
        #-------------------------------------------------------------------------------#   
        echo -e "\n${PSG} ${w}Your startup mode has been detected as ${g}UEFI${h}.\n"  
        Install_Program "$Uefi_grub_Pkg"
        grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=Archlinux --recheck
        grub-mkconfig -o /boot/grub/grub.cfg
        echo;
        if efibootmgr | grep "Archlinux" &>/dev/null ; then
            echo -e "${g} Grub installed successfully -=> [Archlinux] ${h}"  
            echo -e "${g}     $(efibootmgr | grep "Archlinux")  ${h}\n"  
        else
            echo -e "${r} Grub installed failed ${h}"
            echo -e "${g}     $(efibootmgr)  ${h}\n"
        fi
    else  
        echo -e "\n${PSG} ${w}Your startup mode has been detected as ${g}Boot Legacy${h}.\n"  
        Install_Program "$Bios_grub_Pkg"
        local Boot_Partition
        Boot_Partition=$(Query_List _Templist_ Disk) 
        grub-install --target=i386-pc --recheck "${Boot_Partition}"
        grub-mkconfig -o /boot/grub/grub.cfg
        echo;
        if echo $? &>/dev/null ; then
                echo -e "${g} Grub installed successfully -=> [Archlinux] ${h}\n"  
        else
                echo -e "${r} Grub installed failed ${h}\n"
        fi
    fi
}
# 配置本地化 时区 主机名 语音等
function Configure_System(){
    echo -e "${PSG} ${w}Configure enable Network.${h}"    
    systemctl enable NetworkManager  
    echo -e "${PSG} ${w}Time zone changed to 'Shanghai'. ${h}"  
    ln -sf /usr/share/zoneinfo"$Area" /etc/localtime && hwclock --systohc # 将时区更改为"上海" / 生成 /etc/adjtime
    echo -e "${PSG} ${w}Set the hostname 'ArchLinux'. ${h}"
    echo "Archlinux" > /etc/hostname
    # 本地化设置 "英文"
    echo -e "${PSG} ${w}Localization language settings. ${h}"
    sed -i 's/#.*en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen
    echo -e "${PSG} ${w}Write 'en_US.UTF-8 UTF-8' To /etc/locale.gen. ${h}"  
    # 本地化设置 "中文"
    sed -i 's/#.*zh_CN.UTF-8 UTF-8/zh_CN.UTF-8 UTF-8/' /etc/locale.gen 
    echo -e "${PSG} ${w}Write 'zh_CN.UTF-8 UTF-8' To /etc/locale.gen. ${h}" 
    locale-gen
    echo -e "${PSG} ${w}Configure local language defaults 'en_US.UTF-8'. ${h}"  
    echo "LANG=en_US.UTF-8" > /etc/locale.conf       # 系统语言 "英文" 默认为英文   
}
# Install/Configure virtualbox-guest-utils / open-vm-tools
function install_virtualization_service(){
    if [[ "$Virtualization" = "vmware" ]]; then
        pacman -Syu --noconfirm --needed open-vm-tools gtkmm3 gtkmm gtk2 xf86-video-vmware xf86-input-vmmouse
        systemctl enable vmtoolsd.service
        systemctl enable vmware-vmblock-fuse.service
        systemctl start vmtoolsd.service
        systemctl start vmware-vmblock-fuse.service
    else
        pacman -Syu --noconfirm --needed virtualbox-guest-utils
        systemctl enable vboxservice.service
        systemctl start vboxservice.service
    fi 
}
# Nvidia显卡管理器 将PKGBUILD中的github替换了，会快一点【现在该函数未被引用】
function Nvidia_optimus-manager(){
    if [ ! -d ./Pkg/optimus-manager ]; then
        mkdir -p ./Pkg/optimus-manager
        if [ ! -e ./Pkg/optimus-manager/PKGBUILD ]; then
            echo -e "${PSG} ${w}Download ${y}optimus-manager ${w}PKGBUILD.${h}"
            curl -fsSL ${gitUrl}/Auins/raw/master/Pkg/optimus-manager/PKGBUILD > ./Pkg/optimus-manager/PKGBUILD
        fi
    fi
    if [ ! -d ./Pkg/optimus-manager-qt ]; then
        mkdir -p ./Pkg/optimus-manager-qt
        if [ ! -e ./Pkg/optimus-manager-qt/PKGBUILD ]; then
            echo -e "${PSG} ${w}Download ${y}optimus-manager-qt ${w}PKGBUILD.${h}"
            curl -fsSL ${gitUrl}/Auins/raw/master/Pkg/optimus-manager-qt/PKGBUILD > ./Pkg/optimus-manager-qt/PKGBUILD
        fi
    fi
}
# 脚本运行中，临时的命令输出 脚本测试时使用 进入脚本后输入“s”或“shell”
Shell_Exec(){
    local read_text_output
    read_text_output=$(echo -e "${PSY} ${y}Please enter a command or exit():${h} ${JHY}")
    read -rp "${read_text_output}" input_Command

    if [ "$input_Command" = "exit()" ]; then
        bash "$0"
    else
        Exec_Command=$(${input_Command} 2>/dev/null || echo -e "$PSR ${r}auin: command not found: ${y}${input_Command} ${h}") 
        echo "$Exec_Command"
        bash "$0" -shell
    fi
}
# Archlive版本提醒函数，1.30天内不提示，2.超过30天提示更新ISO，3.超过60天提示更新ISO并询问继续使用，4.超过90天提示当前ISO不可以，请更新;
function Archiso_Version_check(){
    Patterns=$(Query_List _Templist_ Patterns) 
    Archiso_Version_Enter="${1}"
    if [ "$Patterns" = "Chroot-OFF" ]; then
            Archiso_Version=$(grep "archisolabel=" < "$Archiso_Version_Enter" | grep -v grep | awk '{print $3}' | cut -d"_" -f2)
            Archiso_Time=$((($(date +%s ) - $(date +%s -d "${Archiso_Version}01"))/86400))
            sed -i "3c Archiso_Version_check = no" "$Configure_tmp_list" 
            if [[ "$Archiso_Time" -gt 121 ]]; then
                clear;
                echo -e "\n${PSR} ${r}You haven't updated in more than 120 days Archiso !${h}\n${PSR} ${r}Archiso Version: ${Archiso_Version}01.${h}"
                echo -e "${PSR} ${r}Please update your archiso !!!  After 10 seconds, Exit(Ctrl+c).${h}"
                sleep 10;
                exit 1;
                sed -i "3c Archiso_Version_check = no" "$Configure_tmp_list" 
            elif [[ "$Archiso_Time" -ge 91 ]]; then
                clear;
                echo -e "\n${PSY} ${y}You haven't updated in more than 90 days Archiso !${h}\n${PSY} ${y}Archiso Version: ${Archiso_Version}01.${h}"
                read -rp "Whether to start the script [Y]: " Version_check
                case $Version_check in
                    [Yy]*)
                        sleep 2;
                    ;;
                    *)
                        echo -e "\n${PSY} ${y}Please update Archiso."
                        exit 1;
                    ;;
                esac
                sed -i "3c Archiso_Version_check = no" "$Configure_tmp_list" 
            elif [[ "$Archiso_Time" -ge 61 ]]; then
                clear;
                echo -e "\n${PSY} ${y}You haven't updated in more than 60 days Archiso !${h}\n${PSY} ${y}Archiso Version: ${Archiso_Version}01.${h}"
                sed -i "3c Archiso_Version_check = yes" "$Configure_tmp_list" 
                sleep 2;
            elif [[ "$Archiso_Time" -ge 31 ]]; then

                clear;
                echo -e "\n${PSY} ${y}Please update as soon as possible Archiso !${h}\n${PSY} ${y}Archiso Version: ${Archiso_Version}01.${h}"
                sed -i "3c Archiso_Version_check = yes" "$Configure_tmp_list" 
                sleep 2;
            fi 
    fi
}
# Stript Management; 脚本进程管理 [start]开启 [restart]重新开启 [stop]杀死脚本进程
function Process_Management(){
    PM_Enter_1=${1}
    PM_Enter_2=${2}
    case ${PM_Enter_1} in
        start)
            bash "${Module}/Process_manage.sh" start "${PM_Enter_2}"
        ;;
        restart)
            bash "${Module}/Process_manage.sh" restart "${PM_Enter_2}"
        ;;
        stop)
            bash "${Module}/Process_manage.sh" stop "${PM_Enter_2}"
            echo -e "\n\n${wg}---------Script Exit---------${h}"  
        ;;
    esac
}
# Start Script
Init_Global_Variable
Color_Global_Variable
facts # Script self-test
System_Config_Global_Variable
Auin_Options "${1}"
Info_Ethernet
Update_Module
if [ "${ChrootPatterns}" = "Chroot-ON" ]; then
    ChrootPatterns="${g}Chroot-ON${h}"
else
    ChrootPatterns="${r}Chroot-OFF${h}"
fi
#----------------------------------------------------------------------------
ECHOA=$(echo -e "${w}          _             _       _     _                    ${h}") 
ECHOB=$(echo -e "${g}         / \   _ __ ___| |__   | |   (_)_ __  _   ___  __  ${h}")
ECHOC=$(echo -e "${b}        / _ \ | '__/ __| '_ \  | |   | | '_ \| | | \ \/ /  ${h}")
ECHOD=$(echo -e "${y}       / ___ \| | | (__| | | | | |___| | | | | |_| |>  <   ${h}")
ECHOE=$(echo -e "${r}      /_/   \_\_|  \___|_| |_| |_____|_|_| |_|\__,_/_/\_\  ${h}")
echo -e "$ECHOA\n$ECHOB\n$ECHOC\n$ECHOD\n$ECHOE" | lolcat 2>/dev/null || echo -e "$ECHOA\n$ECHOB\n$ECHOC\n$ECHOD\n$ECHOE"
echo -e "${b}||============================================================||${h}"
echo -e "${b}|| Script Name:    ${Version}.                                  ${h}"
echo -e "${g}|| Patterns:        ${ChrootPatterns}                           ${h}"
echo -e "${g}|| Ethernet:       ${Ethernet_ip:-No_network..} - [${Ethernet_Name:- }]${h}"
echo -e "${g}|| WIFI:           ${Wifi_ip:-No_network.} - [${Wifi_Name:-No}] ${h}"
echo -e "${g}|| SSH:            ssh $USER@${Ethernet_ip:-IP_Addess.}         ${h}"
echo -e "${g}|| SSH:            ssh $USER@${Wifi_ip:-IP_Addess.}             ${h}"
echo -e "${g}||============================================================||${h}"

echo -e "${PSB} ${g}Configure Mirrorlist   [1]${h}"
echo -e "${PSB} ${g}Configure Network      [2]${h}"
echo -e "${PSG} ${g}Configure SSH          [3]${h}"
echo -e "${PSY} ${g}Install System         [4]${h}"
echo -e "${PSG} ${g}Exit Script            [Q]${h}"

#----------------------------------------------------------------------------
# echo "Script Name:    ${Version}" 
# echo -e "Patterns:        ${ChrootPatterns}"
# echo "Ethernet:       ${Ethernet_ip:-No_network..} - [${Ethernet_Name:- }]"
# echo "WIFI:           ${Wifi_ip:-No_network.} - [${Wifi_Name:-No}]"
# echo "SSH:            ssh $USER@${Ethernet_ip:-IP_Addess.}"
# echo "SSH:            ssh $USER@${Wifi_ip:-IP_Addess.}"
# echo;
# echo "Configure Mirrorlist   [1]"
# echo "Configure Network      [2]"
# echo "Configure SSH          [3]"
# echo "Install System         [4]"
# echo "Exit Script            [Q]"
#----------------------------------------------------------------------------
READS_A=$(echo -e "\n${PSG} ${y} Please enter[1,2,3..] Exit[Q]${h} ${JHB}")
read -rp "${READS_A}" principal_variable 
if [[ ${principal_variable} = 1 ]]; then
    bash "${Module}/mirrorlist.sh"
fi
if [[ ${principal_variable} = 2 ]]; then
    echo -e "\n$w:: Checking the currently available network."; sleep 2;
    echo -e "$w:: Ethernet: ${r}${Ethernet_Name}${h}\n$w:: Wifi:   ${r}${Wifi_Name}${h}"
    READS_B=$(echo -e "${PSG} ${y}Query Network: Ethernet[1] Wifi[2] Exit[3]? ${h}${JHB}")
    read -rp "${READS_B}" wlink 
    case "$wlink" in
        1) 
            Configure_Ethernet
        ;;
        2) 
            Configure_wifi
        ;;
        3) 
            bash "${0}"
        ;;
    esac
fi
if [[ ${principal_variable} = 3 ]]; then
    Open_SSH;
fi
if [[ ${principal_variable} = 4 ]]; then
    input_System_Module
    Output=$(echo -e "${PSG} ${y} Please enter[1,2,21..] Exit[Q] ${h}${JHB}")
    read -rp "${Output}" Tasks
    case ${Tasks} in
    0) # chroot 进入新系统
        Auin_chroot; 
    ;;
    1) #磁盘分区
        clear;partition # 选择磁盘 #parted /dev/sdb mklabel gpt   转换格式 GPT
        clear;partition_root      #root [/]
        partition_booting   #EFI / boot
        partition_swap      #swap file 虚拟文件(类似与win里的虚拟文件) 对于swap分区我更推荐这个，后期灵活更变
        sleep 1
        echo -e "${wg} ::==>> Partition complete. ${h}" 
        bash "${0}" 
    ;;
    2) # 安装及配置系统文件
        Disk_Boot=$(Query_List _Templist_ Root_partition)    # 查 Root_partition
        # 如果"$Temp_Data/auin.info" 文件中Bios_partition存在值 则安装系统
        if [ -n "$Disk_Boot" ]; then 
            Install_Archlinux
        else
            echo -e "${PSR} ${r}The partition is not mounted.${h}"; sleep 3;
            Process_Management restart "$0"
        fi
        sleep 1;echo -e "\n${wg}#======================================================#${h}"
        echo -e "${wg}#::  System components installation completed.         #${h}"            
        echo -e "${wg}#::  Entering chroot mode.                             #${h}"
        echo -e "${wg}#::  Execute in 3 seconds.                             #${h}"
        echo -e "${wg}#::  Later operations are oriented to the new system.  #${h}"
        echo -e "${wg}#======================================================#${h}"
        sleep 3
        echo    # Chroot到新系统中完成基础配置，第一步配置
        cp -rf /etc/pacman.conf /mnt/etc/pacman.conf 
        cp -rf /etc/pacman.d/mirrorlist /mnt/etc/pacman.d/mirrorlist
        Auin_chroot;
    ;;
    3) # 进入系统后的配置
        LinuxKernel=$(Query_List _Templist_ LinuxKernel)    
        if [ -n "$LinuxKernel" ]; then 
            Boot_Package_Variable
            Desktop_Package_Variable
            Install_Font          # 安装字体
            echo;Configure_Grub
            Configure_System
            ConfigurePassworld    # 引用函数：设置密码
            #---------------------------------------------------------------------------#
            echo -e "${ws}#======================================================#${h}" #本区块退出后的提示
            echo -e "${ws}#::                 Exit in 5/s                        #${h}" 
            echo -e "${ws}#::  When finished, restart the computer.              #${h}"
            echo -e "${ws}#::  If there is a problem during the installation     #${h}"
            echo -e "${ws}#::  please contact me. QQ:2763833502                  #${h}"
            echo -e "${ws}#======================================================#${h}"
            sleep 3
        else
            echo -e "${PSR} ${r}The system is not installed. Exec: 4->2 ${h}";sleep 3;
            
            Process_Management restart "$0"
        fi
    ;;
    4) # Installation Desktop. 桌面环境
        ConfigurePassworld    # 引用函数：设置密码
        # Prompt to install desktop environment
        UserName=$(Query_List _Templist_ Users)
        UserHomeDir="/home/${UserName}"
        if [ -n "$UserName" ]; then 
            Desktop_Package_Variable  # Desktop Variable
            Set_Desktop_Env  # Install Desktop
            # Prompt to install driver    
            install_desktop_output=$(echo -e "${PSG} ${y}Whether to install Common Drivers? [y/N]:${h} ${JHB}")
            read -rp "${install_desktop_output}" CommonDrive
            case ${CommonDrive} in
                [Yy]*)
                    Driver_Package_Variable  # 所有驱动Package变量
                    Install_Io_Driver  # 安装驱动函数
                ;;
                [Nn]* )
                    Process_Management stop "$0"
                ;;
            esac
        else
            echo -e "${PSR} ${r}The user is not settings.${h}"; sleep 3;
            Process_Management restart "$0"
        fi
    ;;
    11) # Installation Drive. 驱动, 配置驱动
        Driver_Package_Variable # 所有驱动Package变量
        Install_Io_Driver   # 安装驱动函数
        Install_Processor_Driver # CPU GPU驱动安装函数
    ;;
    22) # Installation VM. open-vm-tools
        echo;install_virtualization_service
        sleep 3; bash "$0"
    ;;
    [Ss]* )
        Shell_Exec
    ;;
    [Qq]*)
        bash "$0"
    ;;
    esac
fi
case ${principal_variable} in
    [Qq]*)
        Process_Management stop "$0"
;;
    [Ss]* )
        Shell_Exec
    ;;
esac
